<?php

namespace App\Exceptions;

use Exception;

class CustomException extends Exception
{
    /**
     * 状态码
     * @var int|mixed
     */
    public $code = 200;

    /**
     * 错误具体信息
     * @var mixed|string
     */
    public $message = 'json';

    /**
     * 构造函数，接收关联数组
     * BaseException constructor.
     * @param array $params
     */
    public function __construct($params = [])
    {
        parent::__construct();
        if (!is_array($params)) {
            return ;
        }
        if (array_key_exists('code', $params)) {
            $this->code = $params['code'];
        }
        if (array_key_exists('msg', $params)) {
            $this->message = $params['msg'];
        }
    }

    public function report()
    {
        // 可以在这里记录日志
    }

    public function render($request)
    {
        // 如果是自定义的异常
        $this->code    = $this->code;
        $this->message = $this->message;
        $result = [
            'code'  => $this->code,
            'msg'   => $this->message,
            'timestamp' => time(),
        ];
        //记录日期
        if ($request->ajax()) {
            return response()->json($result)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        } else {
            return response()->json($result);
        }
    }
}
